package com.clouddisk.file.factory;

import com.clouddisk.common.exception.BusinessException;
import com.clouddisk.file.decorator.impl.CompressionDecorator;
import com.clouddisk.file.decorator.impl.EncryptionDecorator;
import com.clouddisk.file.strategy.FileHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class FileHandlerFactory {

    private final Map<String, FileHandler> fileHandlerMap;

    public FileHandlerFactory(List<FileHandler> fileHandlers) {
        fileHandlerMap = fileHandlers.stream()
                .collect(Collectors.toMap(FileHandler::getFileType, Function.identity()));
    }

    public FileHandler getHandler(MultipartFile file) {
        String contentType = file.getContentType();
        if (contentType == null) {
            throw new BusinessException("无法识别的文件类型");
        }

        String fileType = contentType.split("/")[0];
        FileHandler handler = fileHandlerMap.get(fileType);
        
        if (handler == null) {
            throw new BusinessException("不支持的文件类型");
        }

        if (!handler.isValid(file)) {
            throw new BusinessException("无效的文件格式");
        }

        // 根据文件类型和大小决定是否使用装饰器
        if (shouldCompress(file)) {
            handler = new CompressionDecorator(handler);
        }

        if (shouldEncrypt(file)) {
            handler = new EncryptionDecorator(handler);
        }

        return handler;
    }

    private boolean shouldCompress(MultipartFile file) {
        // 大于1MB的文件进行压缩
        return file.getSize() > 1024 * 1024;
    }

    private boolean shouldEncrypt(MultipartFile file) {
        // 根据文件类型决定是否加密
        String contentType = file.getContentType();
        return contentType != null && (
            contentType.startsWith("application/") ||
            contentType.startsWith("text/")
        );
    }
} 